// 订单状态管理

import { defineStore } from 'pinia'
import type { Order, OrderStatus, OrderItem, Address, CartItem } from '@/types/mall'
import { generateId, getOrderStatusText } from '@/utils/mall'

interface OrderState {
  orders: Order[]
  currentOrder: Order | null
  loading: boolean
  orderStatistics: {
    pendingPayment: number
    pendingShipment: number
    shipped: number
    delivered: number
  }
}

export const useOrderStore = defineStore('order', {
  state: (): OrderState => ({
    orders: [],
    currentOrder: null,
    loading: false,
    orderStatistics: {
      pendingPayment: 0,
      pendingShipment: 0,
      shipped: 0,
      delivered: 0,
    },
  }),

  getters: {
    // 根据状态获取订单列表
    getOrdersByStatus(): (status?: OrderStatus) => Order[] {
      return (status?: OrderStatus) => {
        if (!status) return this.orders
        return this.orders.filter(order => order.status === status)
      }
    },

    // 待付款订单
    pendingPaymentOrders(): Order[] {
      return this.orders.filter(order => order.status === 'pending_payment')
    },

    // 待发货订单
    pendingShipmentOrders(): Order[] {
      return this.orders.filter(order => order.status === 'pending_shipment')
    },

    // 已发货订单
    shippedOrders(): Order[] {
      return this.orders.filter(order => order.status === 'shipped')
    },

    // 已收货订单
    deliveredOrders(): Order[] {
      return this.orders.filter(order => order.status === 'delivered')
    },

    // 已完成订单
    completedOrders(): Order[] {
      return this.orders.filter(order => order.status === 'completed')
    },

    // 已取消订单
    cancelledOrders(): Order[] {
      return this.orders.filter(order => order.status === 'cancelled')
    },

    // 订单总数
    totalOrderCount(): number {
      return this.orders.length
    },

    // 是否有订单
    hasOrders(): boolean {
      return this.orders.length > 0
    },
  },

  actions: {
    // 获取订单列表
    async getOrderList(params?: {
      status?: OrderStatus
      page?: number
      pageSize?: number
    }): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用获取订单列表API
        // const response = await api.order.getOrderList(params)
        // this.orders = response.data.list

        // 模拟订单数据
        if (!params?.page || params.page === 1) {
          this.orders = this.generateMockOrders()
        }

        this.updateOrderStatistics()
        return true
      } catch (error) {
        console.error('Failed to get order list:', error)
        return false
      } finally {
        this.loading = false
      }
    },

    // 获取订单详情
    async getOrderById(orderId: string): Promise<Order | null> {
      try {
        this.loading = true

        // 先从本地查找
        let order = this.orders.find(o => o.id === orderId)
        
        if (!order) {
          // TODO: 从服务器获取订单详情
          // const response = await api.order.getOrderById(orderId)
          // order = response.data
          
          // 模拟订单详情
          order = this.generateMockOrders().find(o => o.id === orderId) || null
          
          if (order) {
            this.orders.push(order)
          }
        }

        this.currentOrder = order
        return order
      } catch (error) {
        console.error('Failed to get order detail:', error)
        return null
      } finally {
        this.loading = false
      }
    },

    // 创建订单
    async createOrder(orderData: {
      items: CartItem[]
      shippingAddress: Address
      paymentMethod?: string
      remark?: string
      couponId?: string
    }): Promise<Order | null> {
      try {
        this.loading = true

        // 构建订单数据
        const orderItems: OrderItem[] = orderData.items.map(item => ({
          id: generateId('order_item_'),
          orderId: '', // 稍后设置
          productId: item.productId,
          skuId: item.skuId,
          product: item.product,
          sku: item.sku,
          quantity: item.quantity,
          price: item.sku?.price || item.product.defaultPrice,
          totalPrice: (item.sku?.price || item.product.defaultPrice) * item.quantity,
        }))

        const totalQuantity = orderItems.reduce((sum, item) => sum + item.quantity, 0)
        const totalPrice = orderItems.reduce((sum, item) => sum + item.totalPrice, 0)

        const newOrder: Order = {
          id: generateId('order_'),
          orderNo: this.generateOrderNo(),
          userId: 'current_user_id', // 从用户store获取
          status: 'pending_payment',
          items: orderItems,
          totalQuantity,
          totalPrice,
          discountAmount: 0,
          shippingFee: totalPrice >= 99 ? 0 : 10, // 满99免运费
          finalPrice: totalPrice + (totalPrice >= 99 ? 0 : 10),
          paymentMethod: orderData.paymentMethod,
          shippingAddress: orderData.shippingAddress,
          remark: orderData.remark,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        }

        // 设置订单项的orderId
        newOrder.items.forEach(item => {
          item.orderId = newOrder.id
        })

        // TODO: 调用创建订单API
        // const response = await api.order.createOrder(newOrder)
        // const createdOrder = response.data

        // 添加到本地订单列表
        this.orders.unshift(newOrder)
        this.currentOrder = newOrder
        this.updateOrderStatistics()

        uni.showToast({ title: '订单创建成功', icon: 'success' })
        return newOrder
      } catch (error) {
        console.error('Failed to create order:', error)
        uni.showToast({ title: '订单创建失败', icon: 'none' })
        return null
      } finally {
        this.loading = false
      }
    },

    // 取消订单
    async cancelOrder(orderId: string, reason?: string): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用取消订单API
        // await api.order.cancelOrder(orderId, reason)

        // 更新本地订单状态
        const order = this.orders.find(o => o.id === orderId)
        if (order) {
          order.status = 'cancelled'
          order.cancelledTime = new Date().toISOString()
          order.cancelReason = reason
          order.updatedAt = new Date().toISOString()
        }

        this.updateOrderStatistics()
        uni.showToast({ title: '订单已取消', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to cancel order:', error)
        uni.showToast({ title: '取消订单失败', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 确认收货
    async confirmOrder(orderId: string): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用确认收货API
        // await api.order.confirmOrder(orderId)

        // 更新本地订单状态
        const order = this.orders.find(o => o.id === orderId)
        if (order) {
          order.status = 'delivered'
          order.deliveryTime = new Date().toISOString()
          order.updatedAt = new Date().toISOString()
        }

        this.updateOrderStatistics()
        uni.showToast({ title: '确认收货成功', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to confirm order:', error)
        uni.showToast({ title: '确认收货失败', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 删除订单
    async deleteOrder(orderId: string): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用删除订单API
        // await api.order.deleteOrder(orderId)

        // 从本地订单列表中删除
        const index = this.orders.findIndex(o => o.id === orderId)
        if (index >= 0) {
          this.orders.splice(index, 1)
        }

        if (this.currentOrder?.id === orderId) {
          this.currentOrder = null
        }

        this.updateOrderStatistics()
        uni.showToast({ title: '订单已删除', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to delete order:', error)
        uni.showToast({ title: '删除订单失败', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 支付订单
    async payOrder(orderId: string, paymentMethod: string): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用支付订单API
        // const response = await api.order.payOrder(orderId, paymentMethod)

        // 更新本地订单状态
        const order = this.orders.find(o => o.id === orderId)
        if (order) {
          order.status = 'pending_shipment'
          order.paymentMethod = paymentMethod
          order.paymentTime = new Date().toISOString()
          order.updatedAt = new Date().toISOString()
        }

        this.updateOrderStatistics()
        uni.showToast({ title: '支付成功', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to pay order:', error)
        uni.showToast({ title: '支付失败', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 再次购买
    async buyAgain(orderId: string): Promise<boolean> {
      try {
        const order = this.orders.find(o => o.id === orderId)
        if (!order) {
          uni.showToast({ title: '订单不存在', icon: 'none' })
          return false
        }

        // TODO: 将订单商品添加到购物车
        // const cartStore = useCartStore()
        // for (const item of order.items) {
        //   await cartStore.addToCart(item.product, item.sku, item.quantity)
        // }

        uni.showToast({ title: '商品已添加到购物车', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to buy again:', error)
        uni.showToast({ title: '操作失败', icon: 'none' })
        return false
      }
    },

    // 更新订单统计
    updateOrderStatistics() {
      this.orderStatistics = {
        pendingPayment: this.orders.filter(o => o.status === 'pending_payment').length,
        pendingShipment: this.orders.filter(o => o.status === 'pending_shipment').length,
        shipped: this.orders.filter(o => o.status === 'shipped').length,
        delivered: this.orders.filter(o => o.status === 'delivered').length,
      }
    },

    // 生成订单号
    generateOrderNo(): string {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      const second = String(now.getSeconds()).padStart(2, '0')
      const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
      
      return `${year}${month}${day}${hour}${minute}${second}${random}`
    },

    // 生成模拟订单数据
    generateMockOrders(): Order[] {
      const mockOrders: Order[] = []
      const statuses: OrderStatus[] = ['pending_payment', 'pending_shipment', 'shipped', 'delivered', 'completed']
      
      for (let i = 0; i < 10; i++) {
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        const order: Order = {
          id: generateId('order_'),
          orderNo: this.generateOrderNo(),
          userId: 'current_user_id',
          status,
          items: [
            {
              id: generateId('order_item_'),
              orderId: '',
              productId: '1',
              product: {
                id: '1',
                name: `商品${i + 1}`,
                description: '商品描述',
                categoryId: '1',
                images: ['https://via.placeholder.com/300x300?text=商品图片'],
                defaultPrice: 9999,
                sales: 100,
                stock: 50,
                status: 'active',
                rating: 4.5,
                reviewCount: 100,
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString(),
              },
              quantity: Math.floor(Math.random() * 3) + 1,
              price: 9999,
              totalPrice: 9999,
            },
          ],
          totalQuantity: 1,
          totalPrice: 9999,
          discountAmount: 0,
          shippingFee: 0,
          finalPrice: 9999,
          shippingAddress: {
            id: generateId('addr_'),
            userId: 'current_user_id',
            name: '张三',
            phone: '13800138000',
            province: '广东省',
            city: '深圳市',
            district: '南山区',
            detail: '科技园南区',
            isDefault: true,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
          },
          createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
          updatedAt: new Date().toISOString(),
        }
        
        order.items[0].orderId = order.id
        mockOrders.push(order)
      }
      
      return mockOrders
    },

    // 清空订单列表
    clearOrders() {
      this.orders = []
      this.currentOrder = null
      this.orderStatistics = {
        pendingPayment: 0,
        pendingShipment: 0,
        shipped: 0,
        delivered: 0,
      }
    },
  },
})